package com.ojoin.ojoin.eb_spider.service.catchdata;



import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.service.SupplyInventoryService;
import com.ojoin.ojoin.eb_spider.service.SupplyPaymentService;
import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.NumberUtils;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;

@Service
public class SupplierYHDDataCatchServiceImpl extends SLDataCatchBaseServiceImpl {

	/** 
	 * 
	 * 1.未结算金额：财务管理》账单管理 结算周期为CLEARINGSCYCLE = 48天。 结算日为6,16,26
	 * 
	 * 统计规则：从结算单生单日期开始算，往后48天。然后结合结款日，得出计算日期。 比如：2015-09-22
	 * 为圣诞日期，则48天后的可结算日期应该是2015-11-10之后.结合结算日，得出结算日期为2015-11-16.
	 * 
	 * 2.库存金额：库存管理》入库单管理 || 退货管理 根据结算单的结算周期，获取最近一次结算的截止日期，然后获取截止日期开始到今天的入库和退货信息
	 * 
	 */

	// 结算周期

	@Autowired
	private SupplyPaymentService paymentService;
	
	@Autowired
	private SupplyInventoryService inventoryService;
	
	private Logger log = LoggerFactory
			.getLogger(SupplierYHDDataCatchServiceImpl.class);

	@Override
	public boolean LoginByUserInfo(String baseUrl, String username,
			String password) throws Exception {

		int loginCount = 1;
		// 开始登陆

		// 开始登陆 最多登陆三次（验证码错误情况）
		String loginReturnMess = ""; // 登陆返回信息
		while (loginCount < verifycodeRetryCount) {
			loginCount++;

			this.getWebDriver().get(baseUrl);

			if(this.getWebDriver().IsDisplayed("css", "#loginForm > div.signIn_switch > a.static_pc")){
				this.getWebDriver().click("css", "#loginForm > div.signIn_switch > a.static_pc");
			}
			
			this.getWebDriver().sendKeys("id", "exactUserName", username);
			this.getWebDriver().sendKeys("id", "originalPassword", password);

			boolean isCome = this.getWebDriver().IsDisplayed("css",
					"#loginForm  div.signIn  p.verification");

			if (isCome) {
				this.verifycode();
			}

			this.getWebDriver().click("id", "submitBtn");

			boolean flag = this.getWebDriver().IsExist("css",
					"body > div.pop-common-dialog.pop-key-notice > div > div.pop-key-notice-txt > div.pop-key-select-btn > a.pop_close.contin-to-keep");
			if(flag){
				this.getWebDriver()
				.findElement(
						"css",
						"body > div.pop-common-dialog.pop-key-notice > div > div.pop-key-notice-txt > div.pop-key-select-btn > a.pop_close.contin-to-keep")
				.click();
			}
			

			if (this.getWebDriver()
					.isLogin("http://supplier.yhd.com/fbyHome/index.action")) {
				return true;
			}
			
			try {

				loginReturnMess = this.getWebDriver()
						.getText(
								"css",
								"#frmLogin > div > div > div.entry-tip.hide > table > tbody > tr > td:nth-child(2) > span");

				if ("输入的验证码错误，请重新输入！".trim().equals(loginReturnMess.trim())
						|| "请输入验证码".trim().equals(loginReturnMess.trim())) {
					// 验证码出错，继续登陆
					this.getWebDriver().sendKeys("id", "pwd", password);

					continue;
				} else if ("输入的验证码错误，请重新输入！".trim().equals(
						loginReturnMess.trim())) {

					LogUtils.info(log, "-->username" + username
							+ "登陆失败-->输入的账户名与密码不匹配%s");
					break;
				} else {
					break;
				}

			} catch (Exception e) {
				// 异常可忽略
				LogUtils.info(log, this.getAssistCatchData().getStartMess().getPlatformUser()
						.getPlatformName()
						+ "-->username"
						+ username
						+ "登陆-->未出现提示信息");
				break;
			}

		}

		return false;
	}

	// 验证码处理
	public void verifycode() throws Exception {
		LogUtils.info(log,  this.getAssistCatchData().getStartMess().getPlatformUser().getPlatformName()
				+ " 登陆界面包含验证码.");
		WebElement verifyE = this.getWebDriver().findElement("id", "imgvalidate");
		if (!CommonUtils.isEmpty(verifyE)) {
			String code = this.getWebDriver().getVerifyCode(verifyE);
			this.getWebDriver().sendKeys("id", "verification", code);
			LogUtils.info(log,  this.getAssistCatchData().getStartMess().getPlatformUser().getPlatformName()
					+ "verifyCode->" + code);
		}

	}

	@Override
	public String catchSupplierName() throws BusinessException {
		String ret = null;
		WebElement titleE = this.getWebDriver()
				.findElement("css",
						"#supplier-main_div_6 > div > p:nth-child(2) > span:nth-child(2)");
		if (null != titleE && StringUtils.isNotEmpty(titleE.getText())) {
			ret = titleE.getText().trim();
		}
		return ret;
	}

	@Override
	public BankCardCheck catchSupplierAccount() throws BusinessException {
		 BankCardCheck bcc = new BankCardCheck();
		String ret = "";
		try {
			String checkBankAccount = "http://supplier.yhd.com/fbycontract/contractList.action?cur_page=userManager";
			this.getWebDriver().get(checkBankAccount);
			WebElement titleE = this.getWebDriver().findElement("css",
					"#showContractList_table_1  tbody  tr  td:nth-child(8)  a");

			String message = titleE.getAttribute("onclick");
			String strids = message.split("\\(")[1];
			String[] ids = strids.split("\\)")[0].split(",");

			String BankAccount = "http://supplier.yhd.com/fbycontract/printContract.action?contractId="
					+ ids[0]
					+ "&mType="
					+ ids[1]
					+ "&canPrint="
					+ ids[2]
					+ "&isStdContract=" + ids[3];

			this.getWebDriver().get(BankAccount);

			this.getWebDriver().waitForPageLoad();
			WebElement title = this.getWebDriver().findElement("css",
					"#contract_MainPart_v3_div_25  font  u");

			if (null != title && StringUtils.isNotEmpty(title.getText())) {
				ret = title.getText().trim();
			}
		} catch (NoSuchElementException e) {
			LogUtils.error(log, "catchSupplierAccount() html 元素查询失败");
		}

		bcc.setBankNum(ret);
		return bcc;
	}

	public boolean getUnpayAccountData() throws BusinessException {
		
		Map<String, TbSlSupplyPayment> waitpay = this.getAssistCatchData().getStartMess().getWaitpay();
		

		List<TbSlSupplyPayment> payments = new ArrayList<TbSlSupplyPayment>();

		String fiveDayPurchase = "http://supplier.yhd.com/supplierfinancial/showAccountsList.action?cur_page=finManager";

		this.getWebDriver().get(fiveDayPurchase);

		WebElement web = this.getWebDriver()
				.findElement(
						"css",
						"#mainDiv  div.contents.clearfix.sp_inventory_list1.sp_goodsmanager_list1  div  div.rm_table  table tbody ");

		List<WebElement> trs = web.findElements(By.tagName("tr"));

		if (null != trs && !trs.isEmpty()) {
			for (int i = 0; i < trs.size(); i++) {

				if (i % 2 != 0) {
					continue;
				}
				WebElement tr = trs.get(i);

				TbSlSupplyPayment payment = new TbSlSupplyPayment();
				payment.setPlatformAccountId( this.getAssistCatchData().getStartMess().getPlatformUser()
						.getId());

				try {

					WebElement invoiceDateE = tr.findElement(By
							.cssSelector("td:nth-child(9)  span"));

					String createDate = invoiceDateE.getText().substring(0, 10);

					WebElement invoiceid = tr.findElement(By
							.cssSelector("td:nth-child(3)  a"));
					WebElement Invoicetatol = tr.findElement(By
							.cssSelector("td:nth-child(6)"));

					WebElement webendtime = tr.findElement(By
							.cssSelector("td:nth-child(5)  span"));

					String endtime = webendtime.getText().trim()
							.substring(13, 23);

					String settlementId = invoiceid.getText();
					String amountD = Invoicetatol.getText().replace(",", "");
					long amount = NumberUtils.getLongAmount(amountD);

					payment.setSettlementId(settlementId);
					payment.setCreateDate(createDate);
					payment.setSettlementDate(endtime);
					payment.setAmount(amount);
					payment.setSettlementState(TbSlSupplyPayment.WAITPAY);

					payments.add(payment);

				} catch (Exception e) {
					if (trs.size() != 1) {
						LogUtils.error(log, "解析结算清单html元素发生错误");
						// throw e;
					}
				}
			}
		}

		paymentService.removeSettlementCommon(payments, waitpay);

		 List<TbSlSupplyPayment> li =paymentService.changeToPay(waitpay);

		 this.getAssistCatchData().getCata().setPayupdate(li);
		 this.getAssistCatchData().getCata().setSettlement(payments);

		return true;
	}

	protected long handleElement2Inv(List<TbSlSupplyInventory> purchases) {
		Map<String, TbSlSupplyInventory> map = new HashMap<String, TbSlSupplyInventory>();
		long result = 0;
		boolean fflag = true;
		while (fflag) {

			try {

				WebElement web = this.getWebDriver().findElement("id", "poList_table_1");

				List<WebElement> trs = web.findElements(By
						.cssSelector("tbody tr"));

				if (null != trs && !trs.isEmpty()) {
					if (trs.size() == 1) {
						WebElement th = null;
						try {
							th = web.findElement(By.cssSelector("tbody tr th"));
						} catch (Exception e) {
						}
						if (null != th)
							return new BigDecimal(result).longValue();
					}
					for (WebElement tr : trs) {
						TbSlSupplyInventory inventory = new TbSlSupplyInventory();
						inventory.setPlatformAccountId( this.getAssistCatchData().getStartMess()
								.getPlatformUser().getId());

						WebElement webStatues = tr.findElement(By
								.cssSelector("td:nth-child(8)"));
						String statues = webStatues.getText();

						if ("已收货".equals(statues)) {
							WebElement invoiceIdE = tr.findElement(By
									.cssSelector("td.hasBorder.sotckNum  a"));

							WebElement store_date = tr.findElement(By
									.cssSelector("td:nth-child(7)"));

							String id = invoiceIdE.getText();

							String key = invoiceIdE.getAttribute("href");

							String time = store_date.getText();

							inventory.setItemId(id);
							inventory.setStoreDate(time.substring(0, 10));
							inventory.setItemKey(id);
							inventory.setItemStatus(TbSlSupplyInventory.IN);

							map.put(key, inventory);

						}
					}
				} else {
					return result;
				}

				WebElement next = this.getWebDriver().findElement("id", "b_nextPage");
				next.click();
				this.getWebDriver().waitForPageLoad();
			} catch (Exception e) {
				break;
			}
		}

		if (null != map && map.size() > 0) {
			Set<Map.Entry<String, TbSlSupplyInventory>> set = map.entrySet();
			Iterator<Map.Entry<String, TbSlSupplyInventory>> it = set
					.iterator();
			while (it.hasNext()) {
				Map.Entry<String, TbSlSupplyInventory> mapen = it.next();
				String url = mapen.getKey();
				TbSlSupplyInventory tbsl = mapen.getValue();
				String pararm = url.split("\\?")[1];

				String realurl = "http://supplier.yhd.com/scm-supplier/fbypo/showPo.action?"
						+ pararm;
				// http://supplier.yhd.com/scm-supplier/fbypo/showPo.action?po.poCode=&po.id=75514969&resNo=GZ801201511230333&taxRate=
				this.getWebDriver().get(realurl);

				WebElement invoiceIdE = this.getWebDriver().findElement("css",
						"#poNewEdit_div_14  p  span  b");

				String amountd = invoiceIdE.getText();
				long amount = NumberUtils.getLongAmount(amountd);

				tbsl.setTotalCost(amount);

				result += amount;
				purchases.add(tbsl);

			}

		}

		return result;
	}

	protected long handleElement2Outv(List<TbSlSupplyInventory> purchases) {
		Map<String, TbSlSupplyInventory> map = new HashMap<String, TbSlSupplyInventory>();
		long result = 0;

		boolean fflag = true;
		while (fflag) {

			try {

				WebElement web = this.getWebDriver().findElement("id", "poList_table_1");

				List<WebElement> trs = web.findElements(By
						.cssSelector("tbody tr"));

				if (null != trs && !trs.isEmpty()) {
					if (trs.size() == 1) {
						WebElement th = null;
						try {
							th = web.findElement(By.cssSelector("tbody tr th"));
						} catch (Exception e) {
						}
						if (null != th)
							return new BigDecimal(result).longValue();
					}
					for (WebElement tr : trs) {
						TbSlSupplyInventory inventory = new TbSlSupplyInventory();
						inventory.setPlatformAccountId( this.getAssistCatchData().getStartMess()
								.getPlatformUser().getId());

						WebElement invoiceIdE = tr.findElement(By
								.cssSelector("td:nth-child(3)  a"));

						WebElement store_date = tr.findElement(By
								.cssSelector("td:nth-child(7)"));

						String id = invoiceIdE.getText();

						String key = invoiceIdE.getAttribute("href");

						String time = store_date.getText();

						inventory.setItemId(id);
						inventory.setStoreDate(time.substring(0, 10));
						inventory.setItemStatus(TbSlSupplyInventory.OUT);
						inventory.setItemKey(id);

						map.put(key, inventory);
					}
				} else {
					return result;
				}

				WebElement next = this.getWebDriver().findElement("id", "b_nextPage");
				next.click();
				this.getWebDriver().waitForPageLoad();

			} catch (Exception e) {
				break;
			}
		}

		if (null != map && map.size() > 0) {
			Set<Map.Entry<String, TbSlSupplyInventory>> set = map.entrySet();
			Iterator<Map.Entry<String, TbSlSupplyInventory>> it = set
					.iterator();
			while (it.hasNext()) {
				Map.Entry<String, TbSlSupplyInventory> mapen = it.next();
				String url = mapen.getKey();
				TbSlSupplyInventory tbsl = mapen.getValue();
				String pararm = url.split("\\?")[1];

				String realurl = "http://supplier.yhd.com/scm-supplier/ro/showPO.action?"
						+ pararm;
				// http://supplier.yhd.com/scm-supplier/fbypo/showPo.action?po.poCode=&po.id=75514969&resNo=GZ801201511230333&taxRate=
				this.getWebDriver().get(realurl);

				WebElement invoiceIdE = this.getWebDriver().findElement("css",
						"#poEdit_div_6  p:nth-child(4)  span:nth-child(2)  b");

				String amountd = invoiceIdE.getText();

				// 金额为负，所以不用乘以-
				long amount = NumberUtils.getLongAmount(amountd);
				tbsl.setTotalCost(amount);

				result += amount;
				purchases.add(tbsl);

			}

		}

		return result;
	}

	@Override
	public boolean getInstoreOrderData() throws BusinessException {
		// 送货记录
		// 对账单
		String starttime =  this.getAssistCatchData().getStartMess().getStoreInStartTime();
		String etime =  this.getAssistCatchData().getStartMess().getStoreInEndTime();

		 Map<String, TbSlSupplyInventory> map = this.getAssistCatchData().getStartMess().getStoreIn();
 
		List<TbSlSupplyInventory> purchases = new ArrayList<TbSlSupplyInventory>();

		String url = "http://supplier.yhd.com/scm-supplier/fbypo/showPoList.action?queryDTO.poOrderDateStart="
				+ starttime + "&queryDTO.poEndTime=" + etime;
		this.getWebDriver().get(url);

		handleElement2Inv(purchases);

		inventoryService.removeInventoryCommon(purchases, map);
		 this.getAssistCatchData().getCata().setInstore(purchases);
		return true;
	}

	@Override
	public boolean getOutstoreOrderData() throws BusinessException {
		// 送货记录
		// 对账单
		String starttime =  this.getAssistCatchData().getStartMess().getStoreOutStartTime();
		String etime =  this.getAssistCatchData().getStartMess().getStoreOutEndTime();

		Map<String, TbSlSupplyInventory> map = this.getAssistCatchData().getStartMess().getStoreOut();

		List<TbSlSupplyInventory> purchases = new ArrayList<TbSlSupplyInventory>();

		String url = "http://supplier.yhd.com/scm-supplier/ro/showList.action?poDTO.poOrderDateStart="
				+ starttime + "&poDTO.poEndTime=" + etime;
		this.getWebDriver().get(url);

		handleElement2Outv(purchases);

		inventoryService.removeInventoryCommon(purchases, map);
		 this.getAssistCatchData().getCata().setOutstore(purchases);
		return true;
	}

	@Override
	public boolean getPayAccountData() throws BusinessException {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public BankCardCheck isSupplyAccountCorrect() throws BusinessException {
		BankCardCheck bcc = new BankCardCheck();
		bcc.setCorrect(true);
		
		return bcc;
	}
}
